import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Carousel } from './entities/carousel.entity';
import { CreateCarouselDto, UpdateCarouselDto } from './dto/carousel.dto';
import { PaginationDto, PaginatedResponseDto } from './dto/pagination.dto';

@Injectable()
export class CarouselService {
  constructor(
    @InjectRepository(Carousel)
    private readonly carouselRepository: Repository<Carousel>,
  ) {}

  async create(createCarouselDto: CreateCarouselDto): Promise<Carousel> {
    const carousel = this.carouselRepository.create(createCarouselDto);
    return this.carouselRepository.save(carousel);
  }

  async findAll(): Promise<Carousel[]> {
    return this.carouselRepository.find({
      order: {
        order: 'ASC',
        createdAt: 'DESC',
      },
    });
  }

  async findAllPaginated(paginationDto: PaginationDto): Promise<PaginatedResponseDto<Carousel>> {
    const { page = 1, limit = 10 } = paginationDto;
    const skip = (page - 1) * limit;

    const [items, total] = await this.carouselRepository.findAndCount({
      order: {
        order: 'ASC',
        createdAt: 'DESC',
      },
      skip,
      take: limit,
    });

    const totalPages = Math.ceil(total / limit);

    return {
      items,
      total,
      totalPages,
      currentPage: page,
      limit,
    };
  }

  async findActive(): Promise<Carousel[]> {
    return this.carouselRepository.find({
      where: { status: true },
      order: {
        order: 'ASC',
        createdAt: 'DESC',
      },
    });
  }

  async findActivePaginated(paginationDto: PaginationDto): Promise<PaginatedResponseDto<Carousel>> {
    const { page = 1, limit = 10 } = paginationDto;
    const skip = (page - 1) * limit;

    const [items, total] = await this.carouselRepository.findAndCount({
      where: { status: true },
      order: {
        order: 'ASC',
        createdAt: 'DESC',
      },
      skip,
      take: limit,
    });

    const totalPages = Math.ceil(total / limit);

    return {
      items,
      total,
      totalPages,
      currentPage: page,
      limit,
    };
  }

  async findOne(id: number): Promise<Carousel> {
    const carousel = await this.carouselRepository.findOne({ where: { id } });
    if (!carousel) {
      throw new NotFoundException(`Carousel with ID ${id} not found`);
    }
    return carousel;
  }

  async update(id: number, updateCarouselDto: UpdateCarouselDto): Promise<Carousel> {
    const carousel = await this.findOne(id);
    this.carouselRepository.merge(carousel, updateCarouselDto);
    return this.carouselRepository.save(carousel);
  }

  async remove(id: number): Promise<void> {
    const carousel = await this.findOne(id);
    await this.carouselRepository.remove(carousel);
  }
} 